import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "ChatRoom", urlPatterns = "/ChatRoom")
public class ChatRoom extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        HttpSession session = request.getSession();
        String chats = context.getAttribute("chats").toString();
        Cookie cookie = new Cookie("count",context.getAttribute("count").toString());
        cookie.setMaxAge(-1);
        session.setMaxInactiveInterval(3);
        response.setContentType("text/html");
        response.setCharacterEncoding("gbk");
        response.addCookie(cookie);
        PrintWriter out = response.getWriter();
        out.println(chats);
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session =  request.getSession();
        ServletContext context = getServletContext();
        String name = session.getAttribute("name").toString();
        String input = request.getParameter("input");
        if(context.getAttribute("chats") == null){
            context.setAttribute("chats","");
        }
        String chats = context.getAttribute("chats").toString();
        context.setAttribute("chats",chats+"~"+name+":"+input);
        System.out.println(context.getAttribute("chats").toString());


        //之前打算用cookie，但是人数一旦多起来就太麻烦，所以改用ajax和servlet直接传数据，反正post闲着

        RequestDispatcher dispatcher = request.getRequestDispatcher("logined.html");
        dispatcher.include(request,response);

    }
}
